package com.bilicute.libman.service.impl;

import com.bilicute.libman.mapper.UserMapper;
import com.bilicute.libman.pojo.User;
import com.bilicute.libman.service.UserService;
import com.bilicute.libman.util.Sha256Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @所属包名: com.bilicute.libman.service.impl
 * @类名: UserServiceImpl
 * @作者: i囡漫笔
 * @描述:
 * @创建时间: 2024-06-18 09:15
 */

@Service
public class UserServiceImpl implements UserService {

    private UserMapper userMapper;

    @Autowired
    private void setUserMapper(UserMapper userMapper){
        this.userMapper = userMapper;
    }

    @Override
    public User findByUserName(String user_name) {
        return userMapper.findByUserName(user_name);
    }

    @Override
    public User getUserByEmail(String mail) {
        return userMapper.getUserByEmail(mail);
    }

    @Override
    public void register(String username, String password,String mail) {
        String passwordEncrypted = Sha256Util.addSalt(password);
        String emailRegex = "^[a-zA-Z\\d_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$";
        Pattern pattern = Pattern.compile(emailRegex);
        Matcher matcher = pattern.matcher(mail);
        if (matcher.matches()) {
            // 分割电子邮件地址以获取用户名和域名
            String[] parts = mail.split("@");
            String domain = parts[1];
            if (domain.equals("bilicute.com")){
                userMapper.register(username,password,mail,"Admin");
                return;
            }
        }
        userMapper.register(username,passwordEncrypted,mail,"User");
    }

    @Override
    public User findByUserId(Integer userId) {
        return userMapper.findByUserId(userId);
    }
}
